package com.dc.di.sf.utils;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.util.Date;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

import com.dc.di.sf.dt.DataUnit;

public class DataTypeUtils {
	
	private static final Logger logger = Logger.getLogger(DataTypeUtils.class);

	public static Object text2Value(String text, String type) {
		try {
			if (DataUnit.TYPE_STRING.equalsIgnoreCase(type))
				return text;
			else if (DataUnit.TYPE_DATETIME.equalsIgnoreCase(type))
				return DateFormat.getDateTimeInstance().parse(text);
			else if (DataUnit.TYPE_DECIMAL.equalsIgnoreCase(type))
				return new BigDecimal(text);
			else if (DataUnit.TYPE_BINARY.equalsIgnoreCase(type))
				return new Base64().decode(text.getBytes());
			else if (DataUnit.TYPE_INTEGER.equalsIgnoreCase(type))
				return new Long(text);
			else if (DataUnit.TYPE_NUMBER.equalsIgnoreCase(type))
				return new Double(text);
			else
				throw new Exception("UnSupport DataType");
		} catch (Exception e) {
			logger.error("text2Value error,text="+text+",type="+type+","+e.getMessage());
		}
		return null;
	}

	public static String value2Text(Object value) {
		if (value instanceof String)
			return (String) value;
		else if (value instanceof Date)
			return DateFormat.getDateTimeInstance().format((Date) value);
		else if (value instanceof Number)
			return value.toString();
		else if (value instanceof byte[])
			return new String(new Base64().encode((byte[]) value));
		else
			return "";
	}

	
	public static void main(String[] a){
		text2Value(null, DataUnit.TYPE_STRING);
		text2Value("", DataUnit.TYPE_STRING);
		
		text2Value(null, DataUnit.TYPE_DATETIME);
		text2Value("", DataUnit.TYPE_DATETIME);
		
		text2Value(null, DataUnit.TYPE_DECIMAL);
		text2Value("", DataUnit.TYPE_DECIMAL);
		
		text2Value(null, DataUnit.TYPE_BINARY);
		text2Value("", DataUnit.TYPE_BINARY);
		
		text2Value(null, DataUnit.TYPE_INTEGER);
		text2Value("", DataUnit.TYPE_INTEGER);
		
		text2Value(null, DataUnit.TYPE_NUMBER);
		text2Value("", DataUnit.TYPE_NUMBER);
	}
}
